package com.atguigu.vodservice.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.*;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.vodservice.service.VodService;
import com.atguigu.vodservice.utils.VideoClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.atguigu.vodservice.utils.ApplicationPropertiesUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 视频点播service
 */
@Service
public class VodServiceImpl implements VodService {

    /**
     * 上传视频到阿里云
     *
     * @param file
     * @return
     */
    @Override
    public String uploadVideo(MultipartFile file) {
        String title = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")); //上传到阿里云后的文件名  去除原始文件名后缀
        String videoId = null;
        try {
            // 获取上传文件的输入流
            InputStream in = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(ApplicationPropertiesUtils.ACCESS_KEY_ID, ApplicationPropertiesUtils.ACCESS_KEY_SECRET, title, file.getOriginalFilename(), in);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else {
                //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                videoId = response.getVideoId();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return videoId;
    }

    /**
     * 根据视频id删除阿里云视频
     *
     * @param videoId
     */
    @Override
    public void deleteVideo(String videoId) {
        try {
            // 使用AccessKeyId初始化获取DefaultAcsClient对象
            DefaultAcsClient client = VideoClient.initVodClient(ApplicationPropertiesUtils.ACCESS_KEY_ID, ApplicationPropertiesUtils.ACCESS_KEY_SECRET);
            DeleteVideoResponse response = new DeleteVideoResponse();
            DeleteVideoRequest request = new DeleteVideoRequest();
            //支持传入多个视频ID，多个用逗号分隔
            request.setVideoIds(videoId);
            response = client.getAcsResponse(request);
        } catch (Exception e) {
            throw new GuliException(20001, "删除视频失败");
        }
    }

    /**
     * 播放视频方式1 url播放 不可播放加密视频
     * 根据视频id获取视频播放地址
     *
     * @param videoId
     * @return
     */
    public String getPlayInfo(String videoId) {
        String playUrl = null;
        try {
            // 使用AccessKeyId初始化获取DefaultAcsClient对象
            DefaultAcsClient client = VideoClient.initVodClient(ApplicationPropertiesUtils.ACCESS_KEY_ID, ApplicationPropertiesUtils.ACCESS_KEY_SECRET);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = new ArrayList<>();
            GetPlayInfoRequest request = new GetPlayInfoRequest();
            request.setVideoId(videoId);
            GetPlayInfoResponse response = client.getAcsResponse(request);
            playInfoList = response.getPlayInfoList();
            List<GetPlayInfoResponse.PlayInfo> list = new ArrayList<>();
            if (null != playInfoList && playInfoList.size() == 1) {
                GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);
                playUrl = playInfo.getPlayURL();
            }
        } catch (Exception e) {
            throw new GuliException(20001, "获取视频播放地址失败");
        }
        return playUrl;
    }

    /**
     * 根据视频id集合批量删除视频
     *
     * @param videoIdList
     */
    @Override
    public void removeVideList(List<String> videoIdList) {
        // 将集合转换成用逗号隔离的字符串
        String videoIds = StringUtils.join(videoIdList.toArray(),",");
        try {
            // 使用AccessKeyId初始化获取DefaultAcsClient对象
            DefaultAcsClient client = VideoClient.initVodClient(ApplicationPropertiesUtils.ACCESS_KEY_ID, ApplicationPropertiesUtils.ACCESS_KEY_SECRET);
            DeleteVideoRequest request = new DeleteVideoRequest();
            //支持传入多个视频ID，多个用逗号分隔
            request.setVideoIds(videoIds);
            DeleteVideoResponse response = client.getAcsResponse(request);
        } catch (Exception e) {
            throw new GuliException(20001, "删除视频失败");
        }
    }

    /**
     * 播放视频方式2 凭证播放 可播放加密视频
     * 根据视频id获取阿里云播放凭证
     * @param videoId
     */
    @Override
    public String getPlayAuth(String videoId){
        String playAuth = null;
        try{
            DefaultAcsClient client = VideoClient.initVodClient(ApplicationPropertiesUtils.ACCESS_KEY_ID, ApplicationPropertiesUtils.ACCESS_KEY_SECRET);
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(videoId);
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            //视频播放凭证
            playAuth = response.getPlayAuth();
        }catch (Exception e){
            throw new GuliException(20001, "获取视频播放凭证失败");
        }
        return playAuth;
    }
}
